package day24;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

//针对集合做序列化
public class Demo7 {
    static List<StudentInfo1> list=new ArrayList<>();
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Scanner sc=new Scanner(System.in);
        System.out.println("1.新增学生");
        System.out.println("2.查询学生");
        System.out.println("3.删除学生");
        int n=sc.nextInt();
        switch (n){
            case 1:add();break;
            case 2:select(); break;
            case 3:delete(); break;
        }
        input();
        output();

    }

    private static void delete() throws IOException, ClassNotFoundException {

    }

    private static void select() throws IOException {
        //反序列化：读取最新数据
        input();
        for (StudentInfo1 info:list){
            System.out.println(info);
        }
    }

    private static void add() throws IOException, ClassNotFoundException {
        //先读取原来的集合
        input();
        list.add(new StudentInfo1(10,"女","123456"));
        //序列化保存最新的集合文件
        output();
    }

    public static void output() throws IOException, ClassNotFoundException {
        try(FileInputStream fis= new FileInputStream("C:\\Users\\梅穿内裤\\Desktop\\IOTest\\aa\\people.abc");
            ObjectInputStream ois= new ObjectInputStream(fis);) {
            list=(List<StudentInfo1>) ois.readObject();
            System.out.println(list);
            fis.close();
            ois.close();
        } catch (FileNotFoundException e) {
            System.out.println("你是第一次使用，没有文件");
        } catch (IOException e){
            e.printStackTrace();
        }

    }
    public static void input() throws IOException {
        FileOutputStream fos=new FileOutputStream("C:\\Users\\梅穿内裤\\Desktop\\IOTest\\aa\\people.abc");
        ObjectOutputStream oos=new ObjectOutputStream(fos);
        oos.writeObject(list);

        fos.close();
        oos.close();
    }
}

class StudentInfo1 implements Serializable {
    Integer id;
    String sex;
    String phone;

    public StudentInfo1(Integer id, String sex, String phone) {
        this.id = id;
        this.sex = sex;
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "StudentInfo{" +
                "id=" + id +
                ", sex='" + sex + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}